package com.tbm.impl.json;

import com.tbm.base.controller.BaseController;
import com.tbm.base.service.SystemUserService;
import com.tbm.common.constant.SessionConstant;
import com.tbm.common.domain.Result;
import com.tbm.common.enums.ResultEnums;
import com.tbm.common.util.PageData;

import com.tbm.common.util.ResultUtil;
import com.tbm.entity.SystemUser;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2017/8/29.
 */
@RestController
public class IndexControllerJson extends BaseController{

    @Autowired
    private SystemUserService systemUserService;

    /**
     *  用户登录验证
     * @author lidq
     * @return
     */
    @RequestMapping("/login-login")
    public Result loginToLogin() {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = this.getPageData();
        String info = "";
        String KEYDATA[] = pd.getString("KEYCODE").split(",");
        if (null != KEYDATA && KEYDATA.length == 2) {
            String USERNAME = KEYDATA[0];
            String PASSWORD = KEYDATA[1];
            //登录验证
            SystemUser sysUser = systemUserService.findByUserName(USERNAME);
            //用户不存在
            if(null == sysUser){
                info = ResultEnums.UNKOWNACCOUNT.getMsg();
            }else{
                SimpleHash simpleHash = new SimpleHash("MD5", PASSWORD, USERNAME, 1024);
                if(!simpleHash.toString().equals(sysUser.getPassword())){
                    info = ResultEnums.INCORRECTCREDENTIALS.getMsg();
                }else{
                    info = ResultEnums.LOGINSUCCESS.getMsg();
                    //存入Session
                    HttpSession session = this.getRequest().getSession();
                    session.setAttribute(SessionConstant.SYSTEMUSER,sysUser);
                    session.setAttribute(SessionConstant.MD5PASSWORD,simpleHash.toString());
                }
            }
        }else{
            info = ResultEnums.USERISNULL.getMsg();
        }
        map.put("result", info);
        return ResultUtil.success(map);
    }
}
